package com.hontlong.aixue.service;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import com.hontlong.aixue.bean.User;

@Service
public class UserService {
	private static final Logger logger = org.slf4j.LoggerFactory
			.getLogger(UserService.class);
	public static User getCurrentUser() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			UserDetails ud = (UserDetails) principal;
			User u = new User();
			u.setUsername(ud.getUsername());
			return u;
		}
		logger.debug(principal.toString());
		return null;
	}

	@Autowired
	private UserDetailsManager userDetailsManager;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private SaltSource saltSource;

	/** 添加用户，对应用户注册 */
	public void addUser(User user) {
		if(userDetailsManager.userExists(user.getUsername())){
			return;
		}
		Object salt = null;
		if (saltSource != null) {
			salt = saltSource.getSalt(user);
		}
		String encodedPassword = passwordEncoder.encodePassword(user
				.getPassword(), salt);
		user.setPassword(encodedPassword);
		try{
			userDetailsManager.createUser(user);
		}catch (Exception e) {
			logger.error("",e);
		}
	}
}
